package com.gitee.sop.adminserver.service.impl;

import com.alibaba.fastjson.JSON;
import com.gitee.sop.adminserver.bean.MetadataEnum;
import com.gitee.sop.adminserver.bean.ServiceInfo;
import com.gitee.sop.adminserver.bean.ServiceInstance;
import com.gitee.sop.adminserver.enums.ZookeeperKeyEnum;
import com.gitee.sop.adminserver.helper.ZookeeperHelper;
import com.gitee.sop.adminserver.service.RegistryService;
import com.i72.basic.SOAServiceAddress;
import com.i72.basic.SOAServiceCenter;
import com.i72.basic.SOAServiceNode;
import com.i72.freeway.StringHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author jiangj
 * @version 1.0.0
 * @ClassName RegistryServiceZookeeperImpl.java
 * @Description TODO
 * @createTime 2021年12月27日 10:53:00
 */
public class RegistryServiceZookeeperImpl implements RegistryService {

    //@Autowired
    //private ZookeeperHelper zookeeperHelper;

    @Autowired
    private SOAServiceCenter soaServiceCenter;

    /*
    @Override
    public List<ServiceInfo> listAllService(int pageNo, int pageSize) throws Exception {

        Map<String,ServiceInfo> serviceInfoMap = zookeeperHelper.getServiceAddresses();
        if(serviceInfoMap!=null && serviceInfoMap.size()>0){
            List<ServiceInfo> serviceInfoList = serviceInfoMap.values().stream().skip((pageNo-1)*pageSize).limit(pageSize).collect(Collectors.toList());

            return serviceInfoList;

        }
        return null;
    }*/


    @Override
    public List<ServiceInfo> listAllService(int pageNo, int pageSize) throws Exception {

        Map<String, SOAServiceAddress> soaServiceAddressMap = soaServiceCenter.getServiceAddresses();

        List<ServiceInfo> serviceInfoList = new ArrayList<>();
        if(soaServiceAddressMap!=null && soaServiceAddressMap.keySet().size()>0){
            List<String> soaKeyList = soaServiceAddressMap.keySet().stream().skip((pageNo-1)*pageSize).limit(pageSize).collect(Collectors.toList());

            soaKeyList.forEach(i->{
                SOAServiceAddress address = soaServiceAddressMap.get(i);

                ServiceInfo serviceInfo = new ServiceInfo();
                serviceInfo.setServiceId(i);
                List<ServiceInstance> instances = new ArrayList<>();
                serviceInfo.setInstances(instances);

                String isOpenPlatform = soaServiceCenter.getConfig(i,"openPlatform");


                if(StringUtils.isNotEmpty(isOpenPlatform)) {


                    Map<String, List<SOAServiceNode>> nodeMap = address.getNodeListMap();

                    for (String nodeType : nodeMap.keySet()) {

                        List<SOAServiceNode> soaServiceNodeList = nodeMap.get(nodeType);

                        if (soaServiceNodeList != null && soaServiceNodeList.size() > 0) {
                            soaServiceNodeList.forEach(j -> {
                                //ServiceInstance instance = new ServiceInstance();

                                ServiceInstance soaServiceNode = new ServiceInstance();

                                soaServiceNode.setServiceId(i);


                                String node = j.getIp();
                                soaServiceNode.setInstanceId(node);
                                try {
                                    if (node.contains(",")) {
                                        soaServiceNode.setIp(node);

                                    } else if (node.contains(":")) {
                                        String[] nodeInfo = node.split(":");
                                        if (nodeInfo.length == 2) {
                                            soaServiceNode.setIp(nodeInfo[0]);
                                            soaServiceNode.setPort(new Integer(nodeInfo[1]));
                                        } else {
                                            soaServiceNode.setIp(node);
                                        }
                                    } else {
                                        soaServiceNode.setIp(node);
                                    }
                                } catch (Exception e) {
                                    String v = "";
                                }
                                String metaDataString = soaServiceCenter.getConfig(i,String.format(ZookeeperKeyEnum.META.getKey(),node));
                                Map<String, String> metadataMap = new HashMap<>();
                                if(StringUtils.isNotEmpty(metaDataString)){
                                    metadataMap= JSON.parseObject(metaDataString,HashMap.class);
                                }
                                //上线：UP，下线：OUT_OF_SERVICE
                                soaServiceNode.setStatus("UP");
                                if(metadataMap.containsKey(ZookeeperKeyEnum.STATUS.getKey())){
                                    soaServiceNode.setStatus(metadataMap.get(ZookeeperKeyEnum.STATUS.getKey()));//上线：UP，下线：OUT_OF_SERVICE
                                }
                                metadataMap.put("nodeType", j.getNodeProperties().toString());
                                soaServiceNode.setMetadata(metadataMap);
                                instances.add(soaServiceNode);
                            });
                        }
                    }

                    if (serviceInfo.getInstances().size() > 0) {
                        serviceInfoList.add(serviceInfo);
                    }
                }
            });
        }
        return serviceInfoList;

    }

    @Override
    public void onlineInstance(ServiceInstance serviceInstance) throws Exception {
        setMetadata(serviceInstance, ZookeeperKeyEnum.STATUS.getKey(), "UP");

    }

    @Override
    public void offlineInstance(ServiceInstance serviceInstance) throws Exception {
        setMetadata(serviceInstance, ZookeeperKeyEnum.STATUS.getKey(), "OUT_OF_SERVICE");
    }

    @Override
    public void setMetadata(ServiceInstance serviceInstance, String key, String value) throws Exception {

        String metaKey = String.format(ZookeeperKeyEnum.META.getKey(),serviceInstance.getInstanceId());
        String metaDataString = soaServiceCenter.getConfig(serviceInstance.getServiceId(),metaKey);
        Map<String, String> metadataMap = new HashMap<>();
        if(StringUtils.isNotEmpty(metaDataString)){
            metadataMap= JSON.parseObject(metaDataString,HashMap.class);
        }
        metadataMap.put(key,value);
        //soaServiceCenter.updateConfig(serviceInstance.getServiceId(),metaKey,JSON.toJSONString(metadataMap));
        SOAServiceCenter.createEphemeralZKNode(String.format("/%s/%s",serviceInstance.getServiceId(),metaKey),JSON.toJSONString(metadataMap));

    }



}
